#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "board.h"

int piece[ROW][COL];
int step;

static int old_r = -1;
static int old_c = -1;

int is_in(int r, int c)
{
	return r >= 0 && r < ROW && c >= 0 && c < COL;
}

int is_empty(int r, int c)
{
	return is_in(r, c) && piece[r][c] == 0;
}


void show_board()
{
	int i, j;

	system("clear");

	printf("  ");
	for (i = 0; i < ROW; ++i)
		printf(" %x ", i);
	printf("\n");

	for (i = 0; i < ROW; ++i)
	{

		printf("%x ", i);
		for (j = 0; j < COL; ++j)
		{
			if (piece[i][j] == 0)
				printf(" %c ", '*');
			else
			{
				if (piece[i][j] == 1)
					printf("\e[37;40m %d \e[0m", piece[i][j]);
				else
					printf("\e[30;47m %d \e[0m", piece[i][j]);

			}
		}
		printf("\n");
	}
	printf("\n");
}

void show_piece(int r, int c, int w)
{
	if (!is_in(r, c))
		return;

	old_r = r;
	old_c = c;

	piece[r][c] = w;
	step += 1;

	show_board();
}


int is_win(int current_row, int current_col)
{
	int i, j, r, c, w;
	int dx[8] = { -1, 0, 1, -1, 1, -1, 0, 1 };
	int dy[8] = { -1, -1, -1, 0, 0, 1, 1, 1 };
	int dn[8] = { 1, 1, 1, 1, 1, 1, 1, 1 };

	if (is_empty(current_row, current_col) || !is_in(current_row, current_col))
		return 0;

	w = piece[current_row][current_col];
	for (i = 0; i < 8; ++i)
	{
		r = current_row;
		c = current_col;
		for (j = 1; j < NUM; ++j)
		{
			r += dy[i];
			c += dx[i];
			if (is_in(r, c) && w == piece[r][c])
				++dn[i];
			else
				break;
		}
	}
	if (dn[0] + dn[7] > NUM || dn[1] + dn[6] > NUM || dn[2] + dn[5] > NUM || dn[3] + dn[4] > NUM)
		return 1;

	return 0;
}

static int todigit(int c)
{
	return (c >= 'a' && c <= 'f') ? c - 'a' + 10 : c - '0';
}

int keyboard_input(int *r, int *c, int w)
{
	char chr, chc;

	scanf("%c%c", &chr, &chc);

	*r = todigit(chr);
	*c = todigit(chc);

	while (getchar() != '\n');

	return is_in(*r, *c) && is_empty(*r, *c);
}
